import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import User from '../entity/user';
import { Repository } from 'typeorm';
import { BaseService } from '../../../common/base.service'
import { BaseError } from '../../../common/base.error';
import { RedisService } from '@midwayjs/redis';
import { RSAService } from '../../../common/rsa.service';
import { ErrorMessageEnums } from '../../../enums/errorMessageEnum';
import { BindStoreDTO } from '../dto/user';
import { StoreManageService } from '../../storeManage/service/storeManage';

@Provide()
export class UserService extends BaseService<User> {

  @Inject()
  rsaService: RSAService

  @Inject()
  redisService: RedisService;

  @Inject()
  storeService: StoreManageService

  @InjectEntityModel(User)
  useModel: Repository<User>;

  getModel(): Repository<User> {
    return this.useModel;
  }

  async createUser(entity: User) {
    try {
      if (!entity.username || !entity.password) {
        throw BaseError.validateError(ErrorMessageEnums.USER_AND_PWD_NOT_NULL);
      }
      const targetUser = await this.getModel().find({
        where: {
          username: entity.username
        },
      });
  
      if (targetUser.length > 0) {
        throw BaseError.validateError(ErrorMessageEnums.USER_EXISTED);
      }
      
      // 密码加密
      entity.password = await this.rsaService.encryptToHash(entity.password);
  
      return await this.getModel().save(entity);
    } catch (err) {
      this.ctx.logger.error(err);
      throw err
    }
  }

  async login(user: User) {
    const loginUser = await this.useModel.find({
      where: {
        username: user.username
      },
    });
    if (loginUser.length > 0) {
      const { password } = loginUser[0];
      const isPwdMatch = await this.rsaService.compareStr(user.password, password);
      if (isPwdMatch) {
        return loginUser[0];
      }
      throw BaseError.validateError(ErrorMessageEnums.USER_OR_PASSWORD_ERROR);
    }

    throw BaseError.validateError(ErrorMessageEnums.USER_NOT_EXIST);
  }

  async pages(page: number, size: number) {
    const [data, total] = await this.getModel().findAndCount();
    console.log('查询：', data, total);
    return {
      data,
      total
    }
  }

  /** 获取用户信息 */
  async getUserInfo() {
    const token = this.ctx.token;
    const userId = await this.redisService.get(`token:${token}`);
    if (!userId) {
      throw BaseError.unauthrizedError(ErrorMessageEnums.LOGIN_IS_EXPIRED)
    }
    const rut = await this.getById(userId);
    return rut
  }

  /** 修改密码 */
  async updatePwd(pwd: string, newPwd: string) {
    try {
      const user = await this.getUserInfo();

      const isOldPwdMath = await this.rsaService.compareStr(pwd, user.password);
      if (!isOldPwdMath) {
        throw BaseError.validateError(ErrorMessageEnums.USER_PASSWORD_ERROR);
      }
  
      user.password = this.rsaService.encryptToHash(newPwd);

      return await this.getModel().save(user)
    } catch (err) {
      throw err
    }
  }

  /** 绑定门店 */
  async bindStore(data: BindStoreDTO) {
    try {
      const { id, storeId } = data;

      const user = await this.getById(id);

      if (!user) {
        throw BaseError.validateError(ErrorMessageEnums.USER_NOT_FOUND);
      }

      if (!storeId) {
        throw BaseError.validateError(ErrorMessageEnums.STORE_NOT_FOUND);
      }

      const store = await this.storeService.getById(storeId);
      if (!store) {
        throw BaseError.validateError(ErrorMessageEnums.STORE_NOT_FOUND);
      }

      user.store = store;

      return await this.edit(user);
    } catch (err) {
      throw err
    }
  }
}
